package com.gl.battleship.services.managers;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.gl.battleship.domain.Position;
import com.gl.battleship.domain.Ship;
import com.gl.battleship.services.Constants;

public class GameManagerHelper {

	//return false if the string has invalid characters
		//return true its all characters valid	
		public static boolean validateCharsFleet(String fleet) {
			for(char charFleet : fleet.toCharArray())
			{
				if( charFleet == Constants.WATER ||
					charFleet == Constants.SHIP_TWO_POSITIONS ||
					charFleet == Constants.SHIP_THREE_POSITIONS ||
					charFleet == Constants.SHIP_FOUR_POSITIONS ||
					charFleet == Constants.SHIP_FIVE_POSITIONS )
				{
					
				}else{
					return false;
				}
			}
			return true;
		}
		
		//return false if the length of ships has invalid
		//return true its all length valid
		public static boolean validateLengthOfShips(String fleet) {
			for(int ships = 0; ships < Constants.NUMBER_OF_SHIPS; ships++)
			{
				//The minimum positions is two
				int numberOfPositions = ships + Constants.MIN_SHIP_POSITIONS;			
					
				//Returns the count of specific subString in a String
				if( numberOfPositions != StringUtils.countMatches(fleet, String.valueOf(numberOfPositions)) )
				{
					return false;
				}
			}
			return true;
		}
		
		//return false if one position has invalid
		//return true its all positions valid
		public static boolean validateShipPositions(List<Ship> shipList) {
				
			for(Ship ship : shipList)
			{
				List<Position> positions = ship.getPositions();
					
				//verify if the ship is horizontal
				boolean mismachSide = true;
				int sideX = positions.get(0).getX();
				
				for (Position pos : positions)
				{
					if(pos.getX() != sideX)
					{
						mismachSide = false;
					}
				}
				
				if(mismachSide)
				{
					for(int pos = 0; pos < positions.size()-1; pos++)
					{
						if((positions.get(pos+1).getY() - positions.get(pos).getY()) != 1 )
						{
							System.out.println(positions.get(pos+1).getY());
							System.out.println(positions.get(pos).getY());
							return false;
						}
					}
				}
				
				if(!mismachSide)
				{
					int sideY = positions.get(0).getY();
					for (Position pos : positions)
					{
						if(pos.getY() != sideY)
						{
							return false;
						}
					}//for
					
					for(int pos = 0; pos < positions.size()-1; pos++)
					{
						if((positions.get(pos+1).getX() - positions.get(pos).getX()) != 1 )
						{
							System.out.println(positions.get(pos+1).getX());
							System.out.println(positions.get(pos).getX());
							return false;
						}	
					}
				}//if
			}//for	
				
			return true;
		}	
}
